package com.wsm.springai.studydemo2.fenxi;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;


@RestController
@RequestMapping("/test")  // 使用 @RequestMapping 来设置基础路径
public class TestController {

    @Autowired
    ChatClient planningChatClient;
    @Autowired
    ChatClient botChatClient;


    @GetMapping(value = "/stream", produces = "text/stream;charset=UTF8")
    public Flux<String> test(@RequestParam String message) {
        Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
        sink.tryEmitNext("正在分析任务，请稍等。。。 <br/>");
        new Thread(() -> {
            AiJob.Job job = planningChatClient.prompt().user(message).call().entity(AiJob.Job.class);
            switch (job.type()){
                case CANCEL ->{
                    System.out.println( job);
                    sink.tryEmitNext("请输入姓名和订单号！ <br/>");
                }
                case QUERY ->{
                    System.out.println( job);
                    sink.tryEmitNext("查询预定信息！ <br/>");
                }
                case OTHER ->{
                    Flux<String> content = botChatClient.prompt().user(message).stream().content();
                    content.doOnNext(sink:: tryEmitNext)
                                    .doOnComplete(sink::tryEmitComplete)
                                            .subscribe();
                }
                default -> {
                    System.out.println( job);
                    sink.tryEmitNext("解析失败");
                }
            }

        }).start(); // 启动线程
        return sink.asFlux();
    }

}
